//
//  RefreshTableViewController.m
//  Tools
//
//  Created by han on 2019/1/16.
//  Copyright © 2019 han. All rights reserved.
//

#import "RefreshTableViewController.h"
#import "RefreshControl.h"

typedef enum : NSUInteger {
    RefreshStateIdle, //闲置状态
    RefreshStatePulling,//下拉状态
    RefreshStateRefreshing,//正在刷新
    RefreshStateEnd,//刷新完成
} RefreshState;
@interface RefreshTableViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) UILabel *refreshLabel;
@property (nonatomic, assign) UIEdgeInsets originInsert;
@property (nonatomic, assign) CGFloat criticalHeight;
@property (nonatomic, assign) RefreshState refreshState;
@end

@implementation RefreshTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.originInsert =  self.tableView.contentInset;
    self.criticalHeight = 50;
    self.refreshLabel = [[UILabel alloc]init];
    [self.tableView addSubview:self.refreshLabel];
    self.refreshLabel.frame = CGRectMake(0, -50, kScreen_Width, 50);
    self.refreshLabel.textAlignment = NSTextAlignmentCenter;
    self.refreshState = RefreshStateIdle;
    self.refreshLabel.lineBreakMode = NSLineBreakByWordWrapping | NSLineBreakByTruncatingTail;
    NSMutableParagraphStyle *style  = [[NSMutableParagraphStyle alloc]init];
    style.lineBreakMode = NSLineBreakByWordWrapping;
    // Do any additional setup after loading the view.
}
#pragma mark --- scrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetY = scrollView.contentOffset.y;
    NSLog(@"scrollView offset Y：%f",offsetY);
    if (offsetY <= - self.criticalHeight - self.originInsert.top) {//下滑至刷新临界值
        if (scrollView.isDragging) {
            if (self.refreshState == RefreshStatePulling) {
//                self.refreshState = RefreshStateIdle;
            }
        }else {
            if (self.refreshState == RefreshStatePulling) {
                self.tableView.contentInset = UIEdgeInsetsMake(self.originInsert.top+self.criticalHeight, 0, 0, 0);
                self.refreshState = RefreshStateRefreshing;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self endRefresh];
                });
            }
        }
    }else {
        //小于临界值
        if (self.refreshState == RefreshStateIdle) {
            self.refreshState = RefreshStatePulling;
        }
    }
}

- (void)endRefresh {
    self.refreshState = RefreshStateEnd;
    [UIView animateWithDuration:0.3 delay:3 options:0 animations:^{
          [self.tableView setContentOffset:CGPointMake(0, self.originInsert.top)];
    } completion:^(BOOL finished) {
          self.refreshState = RefreshStateIdle;
    }];
}

- (void)setRefreshState:(RefreshState)refreshState {
    _refreshState = refreshState;
    switch (refreshState) {
        case RefreshStateIdle:
            self.refreshLabel.text = @"下拉刷新";
            break;
        case RefreshStatePulling:
            self.refreshLabel.text = @"松手刷新";
            break;
        case RefreshStateRefreshing:
            self.refreshLabel.text = @"正在刷新。。。";
            break;
        case RefreshStateEnd:
            self.refreshLabel.text = @"刷新完成";
            break;
        default:
            break;
    }
}

#pragma mark --- tableView delegate & dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"refreshTableIdentifier" forIndexPath:indexPath];
    cell.textLabel.text = [NSString stringWithFormat:@"%zd 行，%zd 列",indexPath.section,indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
